package com.shire.shire_interface.controller.marketing;

import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.common.bin.Response;
import com.shire.shire_interface.controller.BaseController;
import com.shire.shire_interface.model.group.WxGroup;
import com.shire.shire_interface.model.group.WxGroupQrcode;
import com.shire.shire_interface.model.marketing.WxActiveQrcode;
import com.shire.shire_interface.model.marketing.WxActiveQrcodeExample;
import com.shire.shire_interface.model.marketing.WxActiveQrcodeRecord;
import com.shire.shire_interface.model.user.WxAccount;
import com.shire.shire_interface.service.account.WxAccountService;
import com.shire.shire_interface.service.group.impl.WxGroupQrcodeService;
import com.shire.shire_interface.service.marketing.WxActiveQrcodeService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Random;

//@Api(tags = "营销 活码")
@RestController
@RequestMapping("/acitvecode")
public class WxActiveQrcodeController extends BaseController {

    @Resource
    private WxActiveQrcodeService activeQrcodeService;
    @Resource
    private WxGroupQrcodeService wxGroupQrcodeService;
    @Resource
    private WxAccountService wxAccountService;

//    @ApiOperation(value = "保存活码设置")
    @PostMapping("/save")
    public Response updateRecord(@RequestBody WxActiveQrcode record, HttpSession session) {
        Response response = new Response();

        try {

            if (!checkLoginUserByCsId(session, record.getCsid())){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            record.setUpdatetime(new Date());

            if (record.getId() == null) {
                record.setCreatetime(new Date());
            }
            activeQrcodeService.saveWxActiveQrcode(record);

            response.setData(record);
            response.success("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.error("操作失败" + e.getMessage());
        }

        return response;
    }

//    @ApiOperation(value = "查询活码设置，post body: csId, codeType:0个人活码，1群活码")
    @PostMapping("/getRecords")
    public Response getQrcodeRecord(@RequestBody JSONObject jsonObject, HttpSession session) {
        Response response = new Response();
        Integer csId = jsonObject.getInteger("csId");
        Integer codeType = jsonObject.getInteger("codeType");
        try {

            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            WxActiveQrcodeExample example = new WxActiveQrcodeExample();
            example.createCriteria().andCsidEqualTo(csId).andCodetypeEqualTo(codeType).andStatusEqualTo(0);
            example.setOrderByClause("createTime desc");
            addPageParamToExample(jsonObject, example);

            response.setData(activeQrcodeService.getQrCodeRecords(example));
            response.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.error("操作失败" + e.getMessage());
        }

        return response;
    }




    //    @ApiOperation(value = "取活码图片，get  参数： codeId, fingerPrint")
    @GetMapping("/getActiveQrcode")
    public Response getActiveQrcode(@RequestParam(value = "codeId") Integer codeId, @RequestParam(value = "fingerPrint") String fingerPrint) {
        Response response = new Response();
        JSONObject jsonObject = new JSONObject();
        try {
            WxActiveQrcode qrcode = activeQrcodeService.selectQrcodeById(codeId);
            jsonObject.put("bgurl", qrcode.getBgurl());
            if (qrcode.getStatus() != 0) {
                response.error("二维码已过期");
                return response;
            }
            WxActiveQrcodeRecord record = activeQrcodeService.getQrcodeRecord(codeId, fingerPrint);
            if (qrcode.getCodetype() == 1) {
                if (record == null) {
                    int personNum = -1;
                    String groupNo = "";
                    String wxAccount = "";
                    for (WxGroup group : qrcode.getGroups()) {
                        if (group.getPersonnum() > 170)
                            continue;
                        if (personNum < group.getPersonnum()) {
                            wxAccount = group.getWxaccount();
                            groupNo = group.getGroupno();
                            personNum = group.getPersonnum();
                        }
                    }
                    inserQrcodRecord(codeId, fingerPrint, groupNo, wxAccount);

                    WxGroupQrcode groupQrCode = wxGroupQrcodeService.getGroupQrcode(wxAccount, groupNo);
                    jsonObject.put("bgurl", qrcode.getBgurl());
                    if (groupQrCode != null)
                        jsonObject.put("data", groupQrCode.getQrcode());
                    response.setData(jsonObject);
                    response.success("操作成功");
                } else {
                    WxGroupQrcode groupQrCode = wxGroupQrcodeService.getGroupQrcode(record.getWxaccount(), record.getItemid());
                    if (groupQrCode != null)
                        jsonObject.put("data", groupQrCode.getQrcode());
                    response.setData(jsonObject);
                    response.success("操作成功");
                }
            } else {
                if (record == null) {
                    Random random = new Random((new Date()).getTime());
                    int idx = random.nextInt(qrcode.getAccounts().size());
                    WxAccount account = qrcode.getAccounts().get(idx);
                    inserQrcodRecord(codeId, fingerPrint, null, account.getWxid());
                    jsonObject.put("data", account.getQrcode());
                    response.setData(jsonObject);
                    response.success("操作成功");
                } else {
                    WxAccount account = wxAccountService.getWxAccountByWxId(record.getWxaccount());
                    jsonObject.put("data", account.getQrcode());
                    response.setData(jsonObject);
                    response.success("操作成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.error("操作失败" + e.getMessage());
        }

        return response;
    }

    private void inserQrcodRecord(Integer codeId, String finguerPrint, String groupNo, String wxAccount) {
        WxActiveQrcodeRecord qrcodeRecord = new WxActiveQrcodeRecord();
        qrcodeRecord.setFigureid(finguerPrint);
        qrcodeRecord.setItemid(groupNo);
        qrcodeRecord.setWxaccount(wxAccount);
        qrcodeRecord.setQrcodeid(codeId);
        activeQrcodeService.inserQrcodeRecord(qrcodeRecord);
    }
}
